/* 
	product 栏目 - product
 */


/* ------------------------------------------------------------------------------------
	模块导入
------------------------------------------------------------------------------------ */
// 第三方模块 - express
const express = require( 'express' )
/* ------------------------------------------------------------------------------------
	常量、变量、方法
------------------------------------------------------------------------------------ */
// 新建路由
const productRouter = express.Router()
/* ------------------------------------------------------------------------------------
	路由配置
------------------------------------------------------------------------------------ */

/* 
|字段|类型|默认值|注释|主键|
|:----|:-------|:---|---|------|---|
 */

/* ------------------------------------------------------------------------------------
	GET
------------------------------------------------------------------------------------ */

// 根据id获取
productRouter.get( '/getById', async ( req, res ) => res.getById( 'product', 'product_id' ) )

// 获取
productRouter.get( '/get', async ( req, res ) => {
	// 参数
	const {
		product_name
	} = req.query

	// 基础 sql 语句
	let sql = `SELECT * FROM product`

	// 无查询条件，匹配全部
	if ( product_name ) sql += ` WHERE product_name LIKE '%${product_name}%'`

	// 发送 sql
	const product = await res.execSql( sql )

	res.sendResult( {
		product
	}, 200, '获取成功' )
} )

/* ------------------------------------------------------------------------------------
	POST
------------------------------------------------------------------------------------ */

// 添加
productRouter.post( '/add', ( req, res ) => {
	// 参数
	const {
		product_name
	} = req.body
	if ( !product_name ) return res.sendResult( null, 405, '请提供正确参数' )

	res.execSql( `INSERT INTO product SET product_name = '${product_name}')` )
	res.sendResult( null, 200, '添加成功' )
} )

/* ------------------------------------------------------------------------------------
	导出路由
------------------------------------------------------------------------------------ */
module.exports = productRouter
